package com.titaniume.exer;

import org.junit.Test;

/**
 * @program: JavaSenior
 * @description:
 * @author: renfei.huang
 * @create: 2021-10-07 23:18
 */
public class StringDemo {


    @Test
    public void testRevers(){
        String str ="abcdefg";

        String reverse1 = reverse1(str, 2, 5);
        System.out.println(reverse1);

        String reverse2 = reverse2(str, 2, 5);
        System.out.println(reverse2);

        String reverse3 = reverse3(str, 2, 5);
        System.out.println(reverse3);
        System.out.println(reverse3);
    }

    //方式一 从2 到 5 字符串进行交换
    //将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
    public  String reverse1(String str,int startIndex, int endIndex){
        char[] arr = str.toCharArray();
        for (int x = startIndex, y = endIndex; x < y; x++,y--) {
            char temp = arr[x];
            arr[x] = arr[y];
            arr[y] = temp;
        }
        return  new String(arr);
    }




    //方式二：使用String 的拼接
    public  String reverse2(String str,int startIndex, int endIndex){

        //第一部分
        String reverseStr = str.substring(0, startIndex);
        //第二部分
        for (int i = endIndex; i >= startIndex ; i--) {
            reverseStr+=str.charAt(i);
        }
        //第三部分
        reverseStr+= str.substring(endIndex + 1);
        return  reverseStr;
    }

    //方式二：使用StringBuffer/StringBuild 替换Stirng 效率高
    public  String reverse3(String str,int startIndex, int endIndex){

        StringBuilder sb = new StringBuilder(str.length());
        //第一部分
        sb.append(str.substring(0, startIndex));
        //第二部分
        for (int i = endIndex; i >= startIndex ; i--) {
            sb.append(str.charAt(i));
        }
        //第三部分
        sb.append(str.substring(endIndex + 1));

        return  new String(sb);
    }

    @Test
    public void test(){
        String str ="abcdef";
        System.out.println(str.substring(5));
    }
}
